<template>
  <div>
       <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" class="formInline" label-width="60px" slot="form">
                 <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="班级">
                            <el-select v-model="formInline.sClassId" placeholder="请选择" style="width:100%">
                                <el-option v-for="(item,index) in formInline.classArr" :key="index" 
                                :label="item.sNickName" :value="item.pId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" >
                        <el-button type="primary" @click="submit">查询</el-button>
                    </el-col>
                 </el-row>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                     <el-popover placement="bottom-start" trigger="hover" content="点击按钮使用后，所选班级的老师受时间限制，老师只可在开放时间段观看">
                       <el-button @click="batchLimit" slot="reference">批量限制</el-button>
                     </el-popover>
                     <el-popover placement="bottom-start" trigger="hover" content="点击按钮使用后，所选班级的老师不受时间限制，老师可24小时观看">
                        <el-button @click="batchNoLimit" slot="reference">批量不限制</el-button>
                     </el-popover>
                     <el-popover placement="bottom-start" trigger="hover" content="点击按钮使用后，所选班级对家长开放，家长可在开放时间段内观看">
                      <el-button @click="batchOpen" slot="reference">批量开放</el-button>
                     </el-popover>
                     <el-popover placement="bottom-start" trigger="hover" content="点击按钮使用后，所选班级对家长不开放，家长不能观看该班级">
                       <el-button @click="batchNoOpen" slot="reference">批量不开放</el-button>
                     </el-popover>
                     <el-popover placement="bottom-start" trigger="hover" content="点击按钮使用后，将批量对选中班级修改开放时间">
                       <el-button @click="batchChange" slot="reference">批量修改开放时间</el-button>
                     </el-popover>
                </div>
            </div>
            <el-table :data="AnnounceList" border style="width: 100%" @selection-change="handleSelectionChange" ref="multipleTable" v-loading="loading">
                <el-table-column type="selection" width="55" align="center" :selectable="selectable"></el-table-column>
                <el-table-column align="center" label="班级名称" min-width="120" prop="className">
                </el-table-column>
                <el-table-column label="摄像机配置" align="center"  min-width="130">
                     <template scope="scope">
                      <div>{{scope.row.hasClassTimeRule=='1'?'已安装':'未安装'}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="开放时间" align="center" min-width="180">
                    <template scope="scope">
                       <div class="time-open" v-for="(item,index) in scope.row.liveDeviceRule" :key="index">
                          每天{{item.startTime|filterTime}}-{{item.endTime|filterTime}}
                       </div>
                       <div> </div>
                    </template>
                </el-table-column>
                <el-table-column label="是否对家长开放" align="center"  min-width="140">
                    <template scope="scope">
                        <span>{{scope.row.sOpen=='1'?'开放':'不开放'}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否限制老师观看" align="center" prop="limitToTeacher" min-width="150">
                    <template scope="scope">
                        <span>{{scope.row.sFlag=='1'?'限制':'不限制'}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="操作" width="318">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" :disabled="scope.row.hasClassTimeRule=='0'"
                        @click="updateOpenTime(scope.row)">修改开放时间
                        </el-button>
                        <el-button type="text" :disabled="scope.row.hasClassTimeRule=='0'" class="btn-success" 
                        @click="noOpenNoLimit(scope.row)">{{scope.row.sOpen=='1'?'关闭':'开放'}}
                        </el-button>
                        <el-button type="text"  class="btn-success" :disabled="scope.row.hasClassTimeRule=='0'" 
                        @click="limitNoOpen(scope.row)">{{scope.row.sFlag=='1'?'不限制':'限制'}}
                        </el-button>
                        <el-button type="text" class="btn-success" 
                        @click="checkComment(scope.row)">查看评论
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <schoolRegionDialog :addData="addData" @search="searchFetchData"></schoolRegionDialog>
  </div>
</template>
<script>
import TableLayout from 'components/TableLayout';
import schoolRegionDialog from './comp/schoolRegionDialog';
import { mapState, mapActions, mapGetters } from 'vuex';
import { pageClassDevice, 
queryClassBySchool, updateDeviceFlag, updateClassAreaOpen} from 'api/deviceManagement';
import moment from 'moment';
export default {
    name: 'schoolRegion',
    components: { TableLayout, schoolRegionDialog},
    data() {
        return {
            addData: {// 查询 表单数据
                pId: '',
                fClassId: '',
                dialogAdd: false,
                titleIndex: '',
                addOpenTime: [],
                classIds: [], // 批量开放的班级数组id
                isSingleOrBeath: '1' // 1 代表单个 2代表批量
            },
            formInline: {
                schoolName: '',
                classId: '',
                schoolNameList: [],
                classArr: [
                  {className: '', classId: ''}
                ],
                // 参数
                schoolId: null, // 当前学校id
                schoolIds: [], // 学校id数组
                sClassId: ''// 班级id
            },
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            loading: false,
            schoolLoading: false,
            AnnounceList: [], // 后台请求后 把时间段封成数组
            multipleSelection: [], // 勾选的表格的项目
            openStartTimeSecond: false,
            getSchoolInfor: null,
            queryObj: {},
            timeList: null // 时间段数组
        }
    },
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表

        }),
        ...mapGetters([
            'uid',
            'schoolName',
            'schoolId'
        ])
    },
    // 列表页添加watch：
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.searchFetchData();
        }
    },

    created() {
        // 回填学校 查询班级
        this.formInline.schoolName=this.schoolName
        this.formInline.schoolId=this.schoolId;
        this.getclass(this.schoolId)
    },
    filters: {
        filterTime(val) {
            if (val) {
                return val.substring(0, 5)
            }
        }
    },
    methods: {
        ...mapActions(['ChangePageSize']),
        selectable(rows) {// 符合的才可以勾选
            return rows.hasClassTimeRule==='1'
        },
        // 打钩选时
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 点击查看评论
       checkComment(row){
            let id=row.liveDeviceRule[0].fClassId?row.liveDeviceRule[0].fClassId:row.sClassId?row.sClassId:'';
            let status='1';
            this.$router.push({path: `checkComment/${id}/${status}`});
       },
        // 点击批量修改时间
        batchChange() {
            if (this.multipleSelection.length) {// 有勾选的
                this.addData.isSingleOrBeath='2';
                this.addData.dialogAdd=true;
                this.addData.addOpenTime =[{// 默认有一个时间段
                    startTime: '',
                    endTime: ''
                }];
                this.addData.classIds = [];
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    this.addData.classIds.push(this.multipleSelection[i].sClassId) ;
                }
            } else {
                this.$message.info('请选择批量修改的班级')
            }
        },
        getclass() {
            queryClassBySchool(this.schoolId).then(res => {
                this.formInline.classArr=res.data.content;
                if (res.data.content.length) {
                    this.formInline.classArr.unshift({pId: '', sNickName: '请选择'});
                    this.searchFetchData();
                }
            })
        },
        submit() {
            this.listQuery.page = 1;
            this.searchFetchData();
        },
         // 查询列表
        searchFetchData() {
            let page = this.listQuery.page;
            let rows = this.config.pageSize;
            let sClassId = this.formInline.sClassId;
            let schoolIds=[this.schoolId];
            this.loading = true;
            pageClassDevice(page, rows, schoolIds, sClassId).then(res => {
                this.loading = false;
                this.listQuery.total = res.data.content.pagination.total;
                this.AnnounceList = res.data.content.list;
                res.data.content.list.forEach((val, index) => {
                    let liveDeviceRule = val.liveDeviceRule;
                    this.AnnounceList[index].liveDeviceRule=[];
                    if (liveDeviceRule.openStartTimeFirst) {
                        this.AnnounceList[index].liveDeviceRule.push(
                            {
                                startTime: liveDeviceRule.openStartTimeFirst,
                                endTime: liveDeviceRule.openEndTimeFirst,
                                fClassId: liveDeviceRule.fClassId,
                                pId: liveDeviceRule.pId
                            },
                        );
                    }
                    if (liveDeviceRule.openStartTimeSecond) {
                        this.AnnounceList[index].liveDeviceRule.push(
                            {
                                startTime: liveDeviceRule.openStartTimeSecond,
                                endTime: liveDeviceRule.openEndTimeSecond,
                                fClassId: liveDeviceRule.fClassId,
                                pId: liveDeviceRule.pId
                            },
                        );
                    }
                    if (liveDeviceRule.openStartTimeThird) {
                        this.AnnounceList[index].liveDeviceRule.push(
                            {
                                startTime: liveDeviceRule.openStartTimeThird,
                                endTime: liveDeviceRule.openEndTimeThird,
                                fClassId: liveDeviceRule.fClassId,
                                pId: liveDeviceRule.pId
                            },
                        );
                    }
                });
            }).catch(() => {
                this.loading=false
            });
        },
        // pId 是取得rule里面的 没有的话给空    然后fClassId这个字段是先取得rule里面的fClassId，如果他是空 就取外面的list里面的sClassId 
         // 对家长修改开放时间  按钮
        updateOpenTime(row) {
            let currentDate=moment(new Date()).format('YYYY-MM-DD')+' ';// 当前年月日
            this.addData.addOpenTime=[];// 先清空
            this.addData.dialogAdd=true;
            this.addData.isSingleOrBeath='1';
            this.addData.pId=row.liveDeviceRule[0].pId?row.liveDeviceRule[0].pId:'';// 当前列的所有时间段 测完打开
            this.addData.fClassId=row.liveDeviceRule[0].fClassId?row.liveDeviceRule[0].fClassId:row.sClassId?row.sClassId:'';// 当前列的所有时间段 测完打开
            let timeArr=row.liveDeviceRule;
            if (timeArr.length>=1) {
                this.addData.addOpenTime.push(
                    { 
                        startTime: currentDate+timeArr[0].startTime,
                        endTime: currentDate+timeArr[0].endTime
                      
                    }
                );
            }
            if (timeArr.length>=2) {
                this.addData.addOpenTime.push(
                    {
                        startTime: currentDate+timeArr[1].startTime,
                        endTime: currentDate+timeArr[1].endTime
                       
                    }
                );
            }
            if (timeArr.length==3) {
                this.addData.addOpenTime.push(

                    {
                        startTime: currentDate+timeArr[2].startTime,
                        endTime: currentDate+timeArr[2].endTime
                        
                    }
                );
            }
        },
        // 对老师批量限制 sFlag发状态1
        batchLimit() {
            let status='limit';// 表示限制
            this.bathTeacher(status);
        },
         // 对老师批量不限制
        batchNoLimit() {
            let status='noLimit';// 表示不限制
            this.bathTeacher(status);
        },
        // 对老师批量限制或者不限制
        bathTeacher(status) {
            let classIds = [];
            let sClassId=this.schoolId;// 学校id（公共区域）
            let sFlag=status=='limit'?'0':'1';// 限制按钮 发原来的0状态
            let successMsg=status=='limit'?'已限制老师观看！':'已不限制老师观看！';// 默认限制
            for (let i = 0; i < this.multipleSelection.length; i++) {
                let getIds=this.multipleSelection[i].sClassId===null?'':this.multipleSelection[i].sClassId;
                classIds.push(getIds);
            }
            if (classIds.length == 0) {
                this.$message({
                    type: 'info',
                    message: '请选择需要设置的班级!'
                });
                return;
            }
            let warnTitle= sFlag==1?'设置后，老师会变为全天候都可以观看状态，确认设置吗？':'设置后，老师观看的时间段将会与家长的观看时间段相同，确认设置吗？';
            this.$confirm(warnTitle, ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.teaLimit(sClassId, classIds, sFlag, successMsg);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
          // 单个 限制 不开放按钮(限制老师观看)
        limitNoOpen(row) {
            let limit=row.sFlag;// 1 就是限制，0就是不限制
            let sClassId=this.schoolId;// 学校id（公共区域）
            let classIds=[row.sClassId];// 班级id数组（教学区域）
            let sFlag=limit;// /是否老师家长观看时间段相同（1是，0否）直
            let successMsg=sFlag==1?'已不限制老师观看！':'已限制老师观看！';
            let warnTitle= sFlag==1?'设置后，老师会变为全天候都可以观看状态，确认设置吗？':'设置后，老师观看的时间段将会与家长的观看时间段相同，确认设置吗？';
            this.$confirm(warnTitle, ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.teaLimit(sClassId, classIds, sFlag, successMsg);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        // 限制不限制老师
        teaLimit(sClassId, classIds, sFlag, successMsg) {
            updateDeviceFlag(sClassId, classIds, sFlag).then(res => {
                this.$message({
                    type: 'success',
                    message: successMsg
                });
                this.searchFetchData();
            });
        },
          // 对家长批量开放
        batchOpen() {
            let status='open';
            this.bathParent(status);
        },
          // 对家长批量不开放
        batchNoOpen() {
            let status='noOpen';
            this.bathParent(status);
        },
        // 批量时 对家长的操作
        bathParent(status) {
            let classIds=[];// 教学区域是班级id，学校id（公共区域）
            for (let i = 0; i < this.multipleSelection.length; i++) {
                // let getIds=this.multipleSelection[i].sClassId===null?'':this.multipleSelection[i].sClassId;
                let batch=this.multipleSelection;
                let getIds=batch[i].sClassId?batch[i].sClassId:'';
                classIds.push(getIds);
            }
            if (classIds.length == 0) {
                this.$message({
                    type: 'info',
                    message: '请选择需要设置的班级!'
                });
                return;
            }
            let sOpen=status=='open'?'0':'1';// 是否开放（1是，0否）直接取后台返回的值，不做转换
            let successMsg=sOpen=='1'?'已关闭！':'已开放！';
            let warnTitle= sOpen=='1'?'设置后，将不对家长开放，确认设置吗？':'设置后，将会对家长开放，确认设置吗？';
            this.$confirm(warnTitle, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' ', // warning
                title: '  '
            }).then(() => {
                this.parentOpen(classIds, sOpen, successMsg);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
       // 单个操作家长  不开放 和 不限制 按钮（是否对家长开发）
    //    classIds先取rule里面的，没有的话，取外面的
        noOpenNoLimit(row) {
            let openStatus=row.sOpen;
            // let classIds=[this.schoolId];// 学校id（公共区域）
            let id=row.sClassId?row.sClassId:'';
            let classIds=[id];// 学校id（公共区域）
            let sOpen=openStatus// 是否开放（1是，0否）直接取后台返回的值，不做转换
            let successMsg=sOpen=='1'?'已关闭！':'已开放！';
            let warnTitle= sOpen=='1'?'设置后，将不对家长开放，确认设置吗？':'设置后，将会对家长开放，确认设置吗？';
            this.$confirm(warnTitle, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' ', // warning
                title: '  '
            }).then(() => {
                this.parentOpen(classIds, sOpen, successMsg);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
         // 单个操作家长  开放不开放家长
        //   classIds,//学校id（公共区域）
        // sOpen//是否开放（1是，0否）
        parentOpen(classIds, sOpen, successMsg) {
            updateClassAreaOpen(classIds, sOpen).then(res => {
                this.$message({
                    type: 'success',
                    message: successMsg
                });
                this.searchFetchData();
            });
        },
         // 分页
        handleSizeChange(val) {
            this.loading = true;
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        }
    }
}
</script>

<style lang="scss" scoped>
    .formInline {
        .formBtn {
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition {
                position: absolute;
                right: 0px;
                top: 18px;
            }
        }
    }
    .schoolName{
        display:inline-block;
        padding-left:30px;
        font-size:14px;
        color:#333;
        float:left;
        line-height:36px;
    }
</style>

